import axios from 'axios';
import {BASE_URI} from './pathMap';
import {getStorage, setStorage} from "./storage";

const KEY_USERS = "__KEY_USER_LIST"

const instance = axios.create({
	baseURL: BASE_URI,
});

export default {
	get: instance.get,
	post: instance.post,
	
};

/**
 * 更新用户信息
 * @param mobile
 * @param info
 * @returns {Promise<void>}
 */
export const updateUser = (mobile, info) => {
	console.log('updateUser', mobile, info)
	const cacheKey = `${KEY_USERS}_${mobile}`
	return getStorage(cacheKey).then(res=>{
		return setStorage(cacheKey, {
			...res,
			info: {...res.info, ...info}
		})
	})
}

export const login = ({ phone, password }) => {
	const cacheKey = `${KEY_USERS}_${phone}`
	return getStorage(cacheKey)
			.then(res=>{
				if (res?.userId){
					if (res.password !== password){
						return {
							success: false,
							msg: 'phone or password is not right'
						}
					}
					console.log('cache user', res?.mobile, res?.userId, res?.info?.isNew)
					res.token = 'token_'+res.userId;
					if (!res.info){
						res.info = { isNew: true }
					}
					delete res.password
					return {
						success: true,
						data: res,
						msg: 'login success'
					}
				}else {
					const user = {
						userId: Math.ceil(Math.random() * 1000000),
						mobile: phone,
						isNew: true,
						password,
						info: { isNew: true }
					}
					return setStorage(cacheKey, user)
							.then(()=>{
								return {
									success: true,
									msg: 'login success',
									data: {
										...user,
										token: 'token_'+user.userId,
									}
								}
							})
				}

			})


}